//
//  WDNetworking.m
//  Pods
//
//  Created by apple on 2017/5/20.
//
//

#import "WDNetworking.h"
#import "AFNetworking.h"
#import <objc/runtime.h>
static WDNetworking *netWorking = nil;
@interface WDNetworking()
@property (nonatomic, strong) id BaseModel;
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, strong) NSMutableArray *subObjectArr;
@end

@implementation WDNetworking


+(id)netWorkingWithBaseModel:(id)model
{
    WDNetworking *net = [WDNetworking shareInstance];
    net.BaseModel = model;
    return net;
}

+(id)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (netWorking == nil) {
            netWorking = [[WDNetworking alloc] init];
        }
    });
    return netWorking;
}

-(void)POST:(NSString *)baseUrl param:(NSDictionary *)param success:(ReturnBlockModel)success faile:(void(^)(NSError *error))faile
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    [manager POST:baseUrl parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(YES, [self getIvrNameWithObjc:self.BaseModel responseObject:responseObject]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        faile(error);
    }];
}

-(void)GET:(NSString *)baseUrl param:(NSDictionary *)param success:(ReturnBlockModel)success faile:(void(^)(NSError *error)) faile
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    
    [manager GET:baseUrl parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(YES, [self getIvrNameWithObjc:self.BaseModel responseObject:responseObject]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        faile(error);
    }];
}


-(NSMutableArray *)subObjectArr
{
    if (_subObjectArr == nil) {
        _subObjectArr = [NSMutableArray array];
    }
    return _subObjectArr;
}


- (id)getIvrNameWithObjc:(id)objc responseObject:(NSDictionary *)responseObject
{
    NSString *className = [NSString stringWithUTF8String:object_getClassName(objc)];
    Class model = NSClassFromString(className);
    id modelObjec = objc;
    unsigned int count = 0;
    //获取属性的列表
    objc_property_t *propertyList =  class_copyPropertyList([modelObjec class], &count);
    for(int i=0;i<count;i++)
    {
        //取出每一个属性
        objc_property_t property = propertyList[i];
        //获取每一个属性的变量名
        const char* propertyName = property_getName(property);
        const char* propertyAttributes = property_getAttributes(property);
        NSString *proName = [[NSString alloc] initWithCString:propertyName encoding:NSUTF8StringEncoding];
        NSString *key = [NSString stringWithUTF8String:propertyName];
        //生成setter方法
        NSString *usefullStr = [key substringFromIndex:1];          //跳过下划线
        key = [usefullStr capitalizedString];                         //大写首字母
        NSString *firstKey = [[proName substringToIndex:1] capitalizedString];
        NSString *lastStr = [proName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:firstKey];
        key = [NSString stringWithFormat:@"set%@:", lastStr];           //拼接set方法字符串
        SEL setSel = NSSelectorFromString(key);
        if (propertyAttributes[1] == '@' && [responseObject objectForKey:proName] != nil && ![[responseObject objectForKey:proName] isEqual:[NSNull null]]) {
            NSString *getSelString = [NSString stringWithUTF8String:propertyName];
            SEL getSel = NSSelectorFromString(getSelString);
            id value = [modelObjec performSelector:getSel withObject:nil];
            NSString *className = [NSString stringWithUTF8String:object_getClassName(value)];
            if (value != nil && ![value isEqual:[NSNull null]]) {
                id apiValues = [responseObject objectForKey:proName];
                if ([apiValues isKindOfClass:[NSArray class]]) {
                    for (NSDictionary *item in apiValues) {
                        id subObject = [[NSClassFromString(className) alloc] init];
                        id subResult = [self getIvrNameWithObjc:subObject responseObject:item];
                        [self.subObjectArr addObject:subResult];
                    }
                    [modelObjec performSelector:setSel withObject:self.subObjectArr];
                }else if ([apiValues isKindOfClass:[NSDictionary class]]){
                    id subObject = [[NSClassFromString(className) alloc] init];
                    id subResult = [self getIvrNameWithObjc:subObject responseObject:[responseObject objectForKey:proName]];
                    [modelObjec performSelector:setSel withObject:subResult];
                }
            }else{
                if ([modelObjec respondsToSelector:setSel]) {
                    [modelObjec performSelector:setSel withObject:[responseObject objectForKey:proName]];
                }
            }
        }else{
            if ([responseObject objectForKey:proName] != nil && ![[responseObject objectForKey:proName] isEqual:[NSNull null]]) {
                if ([modelObjec respondsToSelector:setSel]) {
                    [modelObjec performSelector:setSel withObject:[responseObject objectForKey:proName]];
                }
            }
        }
    }
    free(propertyList);
    return modelObjec;
}
@end
